package io.github.iogogogo.commons.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * Created by tao.zeng on 2024/11/7.
 */
@Slf4j
public class IpUtils {

    public static List<String> getIpList() {
        try {
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            return Collections.list(enumeration)
                    .stream()
                    .map(x -> Collections.list(x.getInetAddresses())
                            .stream()
                            .filter(InetAddress::isSiteLocalAddress)
                            .map(InetAddress::getHostAddress)
                            .filter(Objects::nonNull)
                            .collect(toList())
                    ).filter(CollectionUtils::isNotEmpty)
                    .flatMap(Collection::stream)
                    .collect(toList());
        } catch (SocketException e) {
            log.error("get ip list failure.", e);
        }
        return Collections.emptyList();
    }
}
